/**
 * 
 */
package com.ws.framework.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ws.framework.model.App;
import com.ws.framework.model.Page;
import com.ws.framework.service.AppService;

/**
 * <p>
 * </p>
 *
 * @author WSH
 */
@Controller
@RequestMapping("app")
public class AppController extends BaseController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	AppService appService;
	
	@RequestMapping("index")
	public String index() {
		return "ftl/appRegister";
	}
	
	@RequestMapping("toList")
	public String toList() {
		return "ftl/appList";
	}
	
	@RequestMapping("/list")
	@ResponseBody
	public Object list(HttpServletRequest request, Page<App> page) {
		Map<String, Object> condition = Maps.newHashMap();
		condition.put("managers", "'%" + this.getUserEntity().getUserName() + "%'");
		page.setCondition(condition);
		return appService.select4Page(page);
	}
	
    /**
     * 
     * 功能描述: <br>
     * 下载一个应用的私钥数据
     * @param appCode 应用appcode
     */
    @RequestMapping(value = "/{appCode}/download")
    public ResponseEntity<String> download(@PathVariable(required = true) String appCode) throws IOException {

        HttpHeaders headers = new HttpHeaders();
        MediaType mt = new MediaType("text", "plain");
        headers.setContentType(mt);
        headers.setContentDispositionFormData("attachment", "app.secretKey");
        App app = appService.selectAppByCode(appCode);
        if (app == null) {
            return null;
        }
        return new ResponseEntity<String>(app.getPriKey(), headers, HttpStatus.CREATED);
    }

	@RequestMapping("register")
	@ResponseBody
	public Object register(@RequestParam("appCode") String appCode, @RequestParam("appName") String appName,
			@RequestParam("codeManager") List<String> codeManagers) {
		try {
			codeManagers = Lists.newArrayList(Collections2.filter(codeManagers, new Predicate<String>() {
				@Override
				public boolean apply(String input) {
					return Strings.isNullOrEmpty(input) ? false : true;
				}
			}));
			if (Strings.isNullOrEmpty(appName) || Strings.isNullOrEmpty(appCode) || codeManagers.isEmpty()) {
				logger.error("App注册请求参数不合法, appCode:{},appName:{},codeMangers:{}", appCode, appName, codeManagers);
				return fail(EnumSvrResult.ERROR_PARAMS);
			}
			appService.insert(new App(appCode, appName, Joiner.on(";").join(codeManagers)));
			return success();
		} catch (DuplicateKeyException e) {
			return fail(EnumSvrResult.ERROR_DUP_KEY);
		} catch (Exception e) {
			logger.error("注册app出现异常", e);
			return error();
		}
	}

}
